<?php
/**
 * 店铺
 *
 * @好商城 (c) 2015-2018 33HAO Inc. (http://www.33hao.com)
 * @license    http://www.33 hao.c om
 * @link       交流群号：138182377
 * @since      好商城提供技术支持 授权请购买shopnc授权
 */


defined('In33hao') or exit('Access Invalid!');

class storeControl extends mobileHomeControl
{
    public function __construct()
    {
        parent::__construct();
    }

    public function my_storeOp()
    {
        $model = Model();
        $member_id = $this->getMemberIdIfExists();
        $field = 'member.store_brokerage,member.av_store_brokerage,store.store_name,store.store_id,store.store_avatar,store.store_banner,store.store_time,store.store_description,store.store_class,store.type,store.store_letters,m_store_banner';
        $on = 'store.member_id=member.member_id';
        $model->table('member,store')->field($field);
        $store_info = $model->join('inner')->on($on)->where(array('member.member_id' => $member_id))->find();
        if (!empty($store_info['m_store_banner'])) {
            $store_info['store_banners'] = explode(',', $store_info['m_store_banner']);
        }
        $open_store = 0;
        if ($store_info) {
            $store_info['member_id'] = $member_id;
            $open_store = 1;
        }
        if (empty($store_info) || $store_info['store_class']) {
            $model_class = Model('goods_class');
            $gcondition['isshow'] = 0;
            $gcondition['is_open'] = 1;
            $gc_id = $model_class->getGoodsClassList($gcondition, 'gc_id');
            $where['gc_id'] = $gc_id[0]['gc_id'];
            $where['buyer_id'] = $member_id;
            $where['order_status'] = ['in', '20,30,40'];
            $res = Model('order_goods')->where($where)->find();
            $open_store = empty($res) ? 0 : 1;
        }
        output_data(array('store_info' => $store_info, 'open_store' => $open_store));
    }

    /**
     * 店铺信息
     */
    public function store_infoOp()
    {
        $store_id = (int)$_REQUEST['store_id'];
        if ($store_id <= 0) {
            $store_id = $_SESSION['store_id'];
        }
        $store_online_info = Model('store')->getStoreOnlineInfoByID($store_id);
        if (empty($store_online_info)) {
            output_error('店铺不存在或未开启');
        }
        $store_info = array();
        $store_info['store_id'] = $store_online_info['store_id'];
        $store_info['store_name'] = $store_online_info['store_name'];
        $store_info['member_id'] = $store_online_info['member_id'];
        $store_info['class_store'] = $store_online_info['store_class'];

        // 店铺头像
        $store_info['store_avatar'] = $store_online_info['store_avatar']
            ? UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $store_online_info['store_avatar']
            : UPLOAD_SITE_URL . '/' . ATTACH_COMMON . DS . C('default_store_avatar');
        if ($store_online_info['m_store_banner']) {
            $store_info['m_store_banner'] = explode(',', $store_online_info['m_store_banner']);
        }
        // 商品数
        $store_info['goods_count'] = (int)$store_online_info['goods_count'];

        // 店铺被收藏次数
        $store_info['store_collect'] = (int)$store_online_info['store_collect'];

        // 如果已登录 判断该店铺是否已被收藏
        if ($memberId = $this->getMemberIdIfExists()) {
            $c = (int)Model('favorites')->getStoreFavoritesCountByStoreId($store_id, $memberId);
            $store_info['is_favorate'] = $c > 0;
        } else {
            $store_info['is_favorate'] = false;
        }

        // 是否官方店铺
        $store_info['is_own_shop'] = (bool)$store_online_info['is_own_shop'];

        // 动态评分
        if ($store_info['is_own_shop']) {
            $store_info['store_credit_text'] = '官方店铺';
        } else {
            $store_info['store_credit_text'] = sprintf(
                '描述: %0.1f, 服务: %0.1f, 物流: %0.1f',
                $store_online_info['store_credit']['store_desccredit']['credit'],
                $store_online_info['store_credit']['store_servicecredit']['credit'],
                $store_online_info['store_credit']['store_deliverycredit']['credit']
            );
        }

        // 页头背景图
        $store_info['mb_title_img'] = $store_online_info['mb_title_img']
            ? UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $store_online_info['mb_title_img']
            : '';

        // 轮播
        $store_info['mb_sliders'] = array();
        $mbSliders = @unserialize($store_online_info['mb_sliders']);
        if ($mbSliders) {
            foreach ((array)$mbSliders as $s) {
                if ($s['img']) {
                    $s['imgUrl'] = UPLOAD_SITE_URL . DS . ATTACH_STORE . DS . $s['img'];
                    $store_info['mb_sliders'][] = $s;
                }
            }
        }

        //店主推荐
        $where = array();
        $where['store_id'] = $store_id;
        $where['goods_commend'] = 1;
        $where['is_book'] = 0;// 默认不显示预订商品
        $model_goods = Model('goods');
        $goods_fields = $this->getGoodsFields();
        $goods_list = $model_goods->getGoodsListByColorDistinct($where, $goods_fields, 'goods_id desc', 0, 20);
        $goods_list = $this->_goods_list_extend($goods_list);
        $store_info['goods_list_count'] = count($goods_list);
        $mydiygoodid_where['store_id'] = $store_id;
        $mydiygoodid_list = Model("my_store")->where($mydiygoodid_where)->select();
        $goodid_arr = '';
        foreach ($mydiygoodid_list as $v) {
            $goodid_arr .= $v['goods_id'] . ",";
        }
        $mydiygood_where['goods_id'] = array('in', trim($goodid_arr, ','));
        $mydiygood_where['goods_state'] = 1;
        $mydiygood_where['goods_verify'] = 1;
        $mydiygood_list = Model()->table('goods')->field($goods_fields)->where($mydiygood_where)->select();
        $mydiygood_list = $this->_goods_list_extend($mydiygood_list);
        foreach ($mydiygood_list as $k => $list) {
            $mydiygood_list[$k]['store_id'] = $store_id;
        }
        $goods_list = array_merge($goods_list, $mydiygood_list);
        foreach ($goods_list as $key => $v) {
            $goods_list[$key]['store_class'] = $store_online_info['store_class'];
        }
        output_data(array(
            'store_info' => $store_info,
            'rec_goods_list_count' => count($goods_list),
            'rec_goods_list' => $goods_list,
        ));
    }

    /**
     * 店铺设置
     */
    public function store_settingOp()
    {
        $memberId = $this->getMemberIdIfExists();
        if (!$memberId) {
            output_error('参数错误');
        }
        $model = Model();
        $store_info = $model->table('store')->where(['member_id' => $memberId])->find();
        if ($store_info) {
            output_error('请勿重复开店');
        }
        $order_id = 0;
        $type = 0;
        if (empty($store_info)) {
            $model_class = Model('goods_class');
            $gcondition['isshow'] = 0;
            $gcondition['is_open'] = 1;
            $gc_id = $model_class->getGoodsClassList($gcondition, 'gc_id');
            $where['gc_id'] = $gc_id[0]['gc_id'];
            $where['buyer_id'] = $memberId;
            $where['order_status'] = ['in', '20,30,40'];
            $res = Model('order_goods')->where($where)->find();
            if (!$res) {
                output_error('非法操作！');
            }
            $order_id = $res['order_id'];
            //根据套餐价格判断开店类型获取相应等级的开店分销比例
            $settings = Model('setting')->getListSetting();
            if ($res['goods_price'] == $settings['fx_st_tc_one']) {
                $type = 1;
            }
            if ($res['goods_price'] == $settings['fx_st_tc_two']) {
                $type = 2;
            }
            if ($res['goods_price'] == $settings['fx_st_tc_three']) {
                $type = 3;
            }
            if ($res['goods_price'] == $settings['fx_st_tc_four']) {
                $type = 4;
            }
        }

        $member_info = Model('member')->getMemberInfoByID($memberId);
        $memberName = $member_info['member_name'];
        $memberletters = $_POST['store_letters'];


        if (!$this->CheckChars($memberletters)) {
            output_error('店铺首字母填写错误');
            die;
        }

        // 更新会员类型
        $updata['type'] = 8;
        $res = Model('member')->editMember(array('member_id' => $memberId), $updata);


        $storeModel = model('store');

        $saveArray = array();
        $saveArray['store_name'] = $_POST['store_name'];
        $saveArray['store_class'] = 0;
        $saveArray['store_letters'] = strtoupper($_POST['store_letters']);
        $saveArray['member_id'] = $memberId;
        $saveArray['member_name'] = $memberName;
        $saveArray['seller_name'] = $memberName;;
        $saveArray['bind_all_gc'] = 1;
        $saveArray['store_state'] = 1;
        $saveArray['store_time'] = time();
        $saveArray['is_own_shop'] = 0;
        $saveArray['type'] = $type;
        $saveArray['store_description'] = $_POST['store_description'];
        if ($_POST['store_avatar']) {
            $saveArray['store_avatar'] = $this->upImgs([$_POST['store_avatar']], BASE_UPLOAD_PATH . '/shop/store')[0];
        }

        // 更新会员类型
        $updata['type'] = 8;
        $res = Model('member')->editMember(array('member_id' => $memberId), $updata);

        $storeId = $storeModel->addStore($saveArray);

        model('seller')->addSeller(array(
            'seller_name' => $memberName,
            'member_id' => $memberId,
            'store_id' => $storeId,
            'seller_group_id' => 0,
            'is_admin' => 1,
        ));

        model('store_joinin')->save(array(
            'seller_name' => $memberName,
            'store_name' => $_POST['store_name'],
            'member_name' => $memberName,
            'member_id' => $memberId,
            'joinin_state' => 40,
            'company_province_id' => 0,
            'sc_bail' => 0,
            'joinin_year' => 1,
        ));

        // 添加相册默认
        $album_model = Model('album');
        $album_arr = array();
        $album_arr['aclass_name'] = '默认相册';
        $album_arr['store_id'] = $storeId;
        $album_arr['aclass_des'] = '';
        $album_arr['aclass_sort'] = '255';
        $album_arr['aclass_cover'] = '';
        $album_arr['upload_time'] = time();
        $album_arr['is_default'] = '1';
        $album_model->addClass($album_arr);

        //插入店铺扩展表
        $model = Model();
        $model->table('store_extend')->insert(array('store_id' => $storeId));

        // 删除自营店id缓存
        Model('store')->dropCachedOwnShopIds();
        dealOpenStore($memberId, $order_id);
        $this->log("新增外驻店铺: {$saveArray['store_name']}");

        output_data(['msg' => '设置成功']);
    }

    //检测是否为字母
    private function CheckChars($str)
    {
        if (empty($str)) return false;
        return (bool)preg_match("/^([a-z\s]*)$/isU", $str);
    }

    /**
     * 店铺商品分类
     */
    public function store_goods_classOp()
    {
        $store_id = (int)$_REQUEST['store_id'];
        if ($store_id <= 0) {
            output_error('参数错误');
        }
        $store_online_info = Model('store')->getStoreOnlineInfoByID($store_id);
        if (empty($store_online_info)) {
            output_error('店铺不存在或未开启');
        }

        $store_info = array();
        $store_info['store_id'] = $store_online_info['store_id'];
        $store_info['store_name'] = $store_online_info['store_name'];

        $store_goods_class = Model('store_goods_class')->getStoreGoodsClassPlainList($store_id);

        output_data(array(
            'store_info' => $store_info,
            'store_goods_class' => $store_goods_class
        ));
    }

    // 检测是否购买了店铺套餐
    public function check_storeOp()
    {
        $member_id = $_SESSION['member_id'];
        if ($member_id <= 0) {
            output_error('参数错误');
        }
        $condition_store['member_id'] = $member_id;
        $store_online_info = Model('store')->getStoreInfo($condition_store);

        if (!empty($store_online_info)) {
            $_SESSION['store_id'] = $store_online_info['store_id'];
            echo 1;
            die;
        }

        $model_class = Model('goods_class');
        $condition['isshow'] = 0;

        $goods_class = $model_class->getGoodsClassList($condition, 'gc_id');
        $gc_idstr = '';
        foreach ($goods_class as $k => $v) {
            $gc_idstr .= $v['gc_id'] . ',';
        }
        $where['gc_id'] = array('in', trim($gc_idstr, ','));
        $where['buyer_id'] = $_SESSION['member_id'];
        $where['order_state'] = ['in', [20, 30, 40]];
        $resulte = Model('order_goods')->where($where)->select();
        if ($resulte) {
            echo 1;
        } else {
            echo 0;
        }
    }

    // 自选商品列表
    public function storeGoodsListOp()
    {
        $memberId = $this->getMemberIdIfExists();
        $where['member_id'] = $memberId;
        $store_info = Model('store')->getStoreInfo($where);
        $mystore = Model('my_store')->where(array('store_id' => $store_info['store_id']))->select();
        $goodsModel = Model('goods');
        $goodsId = "";
        foreach ($mystore as $v) {
            $goodsId .= $v['goods_id'] . ",";
        }
        $condition['goods_id'] = array('in', trim($goodsId, ','));
        $goodslist = $goodsModel->getGoodsList($condition);
        foreach ($goodslist as $key => $v) {
            $goodslist[$key]['goods_image'] = thumb($v);
        }
        output_data(array('goodslist' => $goodslist));
    }

    // 获取店铺信息
    public function getStoreInfoOp()
    {
        $member_id = $_SESSION['member_id'];
        if ($member_id <= 0) {
            output_error('参数错误');
        }
        $condition_store['member_id'] = $member_id;

        $store_online_info = Model('store')->getStoreInfo($condition_store);
        if (empty($store_online_info)) {
            output_error('店铺不存在或未开启');
        }
//
        $store_info = array();
        $store_info['store_id'] = $store_online_info['store_id'];
        $store_info['store_name'] = $store_online_info['store_name'];
        $store_info['member_id'] = $store_online_info['member_id'];
        $store_info['member_name'] = $store_online_info['member_name'];
        $store_info['class_store'] = $store_online_info['store_class'];
        $store_info['create_time'] = date("Y-m-d H:i:s", $store_online_info['store_time']);

        // 店铺头像
        $store_info['store_avatar'] = $store_online_info['store_avatar']
            ? UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $store_online_info['store_avatar']
            : UPLOAD_SITE_URL . '/' . ATTACH_COMMON . DS . C('default_store_avatar');

        // 商品数
        $store_info['goods_count'] = (int)$store_online_info['goods_count'];
        output_data(array('store_info' => $store_info));
    }

    // 获取店铺信息
    public function getSqStoreInfoOp()
    {
        $store_id = $_GET['sqstore_id'];
        if ($store_id <= 0) {
            output_error('参数错误');
        }
        $condition_store['store_id'] = $store_id;

        $store_online_info = Model('store')->getStoreInfo($condition_store);
        if (empty($store_online_info)) {
            output_error('店铺不存在或未开启');
        }
//
        $store_info = array();
        $store_info['store_id'] = $store_online_info['store_id'];
        $store_info['store_name'] = $store_online_info['store_name'];
        $store_info['member_id'] = $store_online_info['member_id'];
        $store_info['member_name'] = $store_online_info['member_name'];
        $store_info['class_store'] = $store_online_info['store_class'];
        $store_info['store_banner'] = $store_online_info['store_banner'];
        $store_info['store_time'] = $store_online_info['store_open_time'];
        $store_info['store_tel'] = $store_online_info['store_tel'];

        $store_info['create_time'] = date("Y-m-d H:i:s", $store_online_info['store_time']);
        if ($store_online_info['m_store_banner']) {
            $store_info['m_store_banners'] = explode(',', trim($store_online_info['m_store_banner']));
        }
        $model_store_map = Model('store_map');
        $condition['store_id'] = $store_online_info['store_id'];
        $map_list = $model_store_map->getStoreMapList($condition, 10, '', 'map_id asc');
        if ($map_list) {
            $store_info['store_map'] = $map_list['0'];
        }
        // 店铺头像
        $store_info['store_avatar'] = $store_online_info['store_avatar']
            ? UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $store_online_info['store_avatar']
            : UPLOAD_SITE_URL . '/' . ATTACH_COMMON . DS . C('default_store_avatar');
        output_data(array('store_info' => $store_info));
    }

    /**
     * 保存商圈店铺信息
     */
    public function saveSqStoreOp()
    {
        $memberId = $this->getMemberIdIfExists();
        $where['member_id'] = $memberId;
        $store_info = Model('store')->getStoreInfo($where);
        $name = $_POST['name'];
        $time = htmlspecialchars($_POST['time']);
        $address = htmlspecialchars($_POST['address']);
        $tel = $_POST['tel'];
        if ($name == '') {
            return ['status' => 400, 'msg' => '店铺信息不能为空'];
        }
        $inserdata['store_name'] = $name;
        $inserdata['store_tel'] = $tel;
        $inserdata['store_open_time'] = $time;
        $condition['store_id'] = $store_info['store_id'];
        $res = Model('store')->editStore($inserdata, $condition);

        // 如果地址传过来了
        if (!empty($address)) {
            $isUpdataAddress = 1;
            $updata['address_info'] = $address;
            $updata['name_info'] = $name;
            $updata['phone_info'] = $tel;
            $updata['store_id'] = $store_info['store_id'];
            $updata['sc_id'] = 0;
            $updata['update_time'] = time();
            $updata['baidu_lng'] = $_POST['lang'] ? $_POST['lang'] : 0;
            $updata['baidu_lat'] = $_POST['lat'] ? $_POST['lang'] : 0;
            $updata['baidu_province'] = $_POST['pro'] ? $_POST['lang'] : '';
            $updata['baidu_city'] = $_POST['city'] ? $_POST['lang'] : '';
            $updata['baidu_district'] = $_POST['dis'] ? $_POST['lang'] : '';
            $updata['baidu_street'] = $_POST['street'] ? $_POST['lang'] : '';
            $mapcondition['map_id'] = $_POST['map_id'] ? $_POST['lang'] : 0;
            $reslut = false;
            if ($mapcondition['map_id']) {
                $reslut = Model('store_map')->editStoreMap($mapcondition, $updata);
            } else {
                $reslut = Model('store_map')->addStoreMap($updata);
            }
            if ($reslut) {
                $isUpdata = 1;
            }
        }

        if ($isUpdataAddress) {
            if ($res && $isUpdata) {
                $res = ['status' => 200, 'msg' => '店铺信息修改成功'];
            } else {
                $res = ['status' => 400, 'msg' => '店铺信息修改失败'];
            }
        } else {
            if ($res) {
                $res = ['status' => 200, 'msg' => '店铺信息修改成功'];
            } else {
                $res = ['status' => 400, 'msg' => '店铺信息修改失败'];
            }
        }
        output_data($res);
    }

    /**
     * 从我的小店里删除商品
     */
    public function delgoodsOp()
    {
        $id = $_POST['id'];
        $res = Model('my_store')->where(array("goods_id" => $id, 'store_id' => $_SESSION['store_id']))->delete();
        if ($res) {
            echo 1;
            die;
        }
        echo 0;
    }

    /**
     * 商圈首页
     */
    public function business_storeOp()
    {
        // 获取商圈顶级分类
        $tag = "商圈";
        $business_goods_class = Model("goods_class")->getGoodsClassList(array('gc_name' => $tag), 'gc_id');
        // 获取商圈下级分类
        $condition_b_class['gc_virtual'] = 1;
        $condition_b_class['gc_parent_id'] = $business_goods_class[0]["gc_id"];
        $business_b_class = Model("goods_class")->getGoodsClassList($condition_b_class);
        //获取banner
        $sq_banner = Model('sq_setting');
        $bannerList = $sq_banner->getBannerList(array());
        foreach ($bannerList as $key => $value) {
            $bannerList[$key]['pic'] = UPLOAD_SITE_URL . '/' . ATTACH_MOBILE . '/sqbanner' . '/' . $value['images'];
        }
        if ($_GET['page']) {
            $page = $_GET['page'];
        } else {
            $page = 1;
        }
        $where = 'store_class=1 AND store_state=1';
        if (!$_GET['name']) {
            if ($_GET['province_id']) {
                $where .= " AND province_id=" . $_GET['province_id'];
            }
            if ($_GET['city_id']) {
                $where .= " AND city_id=" . $_GET['city_id'];
            }
            if ($_GET['disid']) {
                $where .= " AND area_id=" . $_GET['disid'];
            }
        } else {
            $where .= " AND area_info like '%" . $_GET['name'] . "%'";
        }
        //获取商圈店铺列表
        $pagesize = 10;
        $start = ($page - 1) * $pagesize;
        $sql = "select * from 33hao_store WHERE $where limit $start,$pagesize";
        $business_store = Model()->query($sql);
        // 获取店铺销量
        foreach ($business_store as $k => $v) {
            $store_id = $v['store_id'];
            $model_store_map = Model('store_map');
            $g_condition['store_id'] = $store_id;
            $map_list = $model_store_map->getStoreMapList($g_condition, 10, '', 'map_id asc');

            // 查询该店铺的 所有商品
            $store_goods_list = Model('goods')->getGoodsList($g_condition, "goods_salenum");
//              // 计算销量
            $business_store[$k]['salenum'] = empty($this->calculateSales($store_goods_list)) ? 0 : $this->calculateSales($store_goods_list);
            $business_store[$k]['store_address'] = $map_list['0']['address_info'];
        }
        // 对地址进行排序
        $_noEmtemp = array();
        $_Empty = array();
        foreach ($business_store as $v) {
            if ($v['store_address']) {
                $_noEmtemp[] = $v;
            } else {
                $_Empty[] = $v;
            }
        }
        $business_store = array_merge($_noEmtemp, $_Empty);
        output_data(array(
            'class_data' => $business_b_class,
            'business_store' => $business_store,
            'banner' => $bannerList
        ));
    }

    //自助开店套餐列表
    public function auto_storelistOp()
    {
        $model_class = Model('goods_class');
        $total_page = pagecmd('gettotalpage');
        if (intval($_GET['curpage'] > $total_page)) {
            exit();
        }
        $condition['isshow'] = 0;
        $condition['is_open'] = 1;
        $goods_class = $model_class->getGoodsClassList($condition, 'gc_id');
        $gc_idstr = '';
        foreach ($goods_class as $k => $v) {
            $gc_idstr .= $v['gc_id'] . ',';
        }
        $where['gc_id'] = array('in', trim($gc_idstr));
        $where['goods_state'] = 1;
        $data = Model('goods')->getGoodsList($where);
        output_data($data);
    }

    /**
     * 店铺商品
     */
    public function store_goodsOp()
    {
        $param = $_REQUEST;

        $store_id = (int)$param['store_id'];
        if ($store_id <= 0) {
            output_error('参数错误');
        }
        $stc_id = (int)$param['stc_id'];
        $keyword = trim((string)$param['keyword']);

        $condition = array();
        $condition['store_id'] = $store_id;

        // 默认不显示预订商品
        $condition['is_book'] = 0;

        if ($stc_id > 0) {
            $condition['goods_stcids'] = array('like', '%,' . $stc_id . ',%');
        }
        //促销类型
        if ($param['prom_type']) {
            switch ($param['prom_type']) {
                case 'xianshi':
                    $condition['goods_promotion_type'] = 2;
                    break;
                case 'groupbuy':
                    $condition['goods_promotion_type'] = 1;
                    break;
            }
        }
        if ($keyword != '') {
            $condition['goods_name'] = array('like', '%' . $keyword . '%');
        }
        $price_from = preg_match('/^[\d.]{1,20}$/', $param['price_from']) ? $param['price_from'] : null;
        $price_to = preg_match('/^[\d.]{1,20}$/', $param['price_to']) ? $param['price_to'] : null;
        if ($price_from && $price_from) {
            $condition['goods_promotion_price'] = array('between', "{$price_from},{$price_to}");
        } elseif ($price_from) {
            $condition['goods_promotion_price'] = array('egt', $price_from);
        } elseif ($price_to) {
            $condition['goods_promotion_price'] = array('elt', $price_to);
        }

        // 排序
        $order = (int)$param['order'] == 1 ? 'asc' : 'desc';
        switch (trim($param['key'])) {
            case '1':
                $order = 'goods_id ' . $order;
                break;
            case '2':
                $order = 'goods_promotion_price ' . $order;
                break;
            case '3':
                $order = 'goods_salenum ' . $order;
                break;
            case '4':
                $order = 'goods_collect ' . $order;
                break;
            case '5':
                $order = 'goods_click ' . $order;
                break;
            default:
                $order = 'goods_id desc';
                break;
        }

        $model_goods = Model('goods');

        $goods_fields = $this->getGoodsFields();
        $goods_list = $model_goods->getGoodsListByColorDistinct($condition, $goods_fields, $order, $this->page);
        $page_count = $model_goods->gettotalpage();

        $goods_list = $this->_goods_list_extend($goods_list);

        output_data(array(
            'goods_list_count' => count($goods_list),
            'goods_list' => $goods_list,
        ), mobile_page($page_count));
    }

    /**
     * 虚拟订单列表
     */
    public function vr_order_listOp()
    {
        $member_id = $_SESSION['member_id'];
        // 店铺id
        $condition_store['member_id'] = $member_id;
        $store_online_info = Model('store')->getStoreInfo($condition_store);
        $model_vr_order = Model("vr_order");
        $condition['store_id'] = $store_online_info['store_id'];
        $page = $_GET['page'] ? $_GET['page'] : 1;
        $limt = 10;
        $start = ($page - 1) * $limt;
        if ($_GET['use_state']) {
            $usd = $_GET['use_state'];
        } else {
            $usd = 0;
        }
        $sql = "SELECT * from 33hao_vr_order WHERE store_id=" . $store_online_info['store_id'] . " and use_state=$usd order by add_time DESC limit $start,$limt";
        $order_list = Model()->query($sql);
        //查询消费者保障服务
        if (C('contract_allow') == 1) {
            $contract_item = Model('contract')->getContractItemByCache();
        }

        foreach ($order_list as $key => $order) {
            //处理消费者保障服务
            if (trim($order['goods_contractid']) && $contract_item) {
                $goods_contractid_arr = explode(',', $order['goods_contractid']);
                foreach ((array)$goods_contractid_arr as $gcti_v) {
                    $order['contractlist'][] = $contract_item[$gcti_v];
                }
            }
            $order_list[$key] = $order;
            //显示取消订单
            $order_list[$key]['if_cancel'] = $model_vr_order->getOrderOperateState('buyer_cancel', $order);

            //追加返回买家信息
            $order_list[$key]['extend_member'] = Model('member')->getMemberInfoByID($order['buyer_id']);
        }
        foreach ($order_list as $k => $v) {
            $order_list[$k]['goods_img'] = thumb($v, 60);
            $order_list[$k]['time'] = date("Y-m-d H:i:s", $v['add_time']);
        }
        if (!empty($order_list)) {
            echo json_encode(array("list" => $order_list));
        } else {
            echo json_encode(0);
        }
    }

    /**
     * 读取线下订单
     */
    public function offline_order_listOp()
    {

        $condition['store_id'] = $_GET['store_id'];
        $limt = 10;
        $page = $_GET['page'] ? $_GET['page'] : 1;
        $start = ($page - 1) * $limt;
        $sql = "SELECT * from 33hao_offline_order WHERE store_id=" . $_GET['store_id'] . " order by add_time DESC limit $start,$limt";
        $order_list = Model()->query($sql);
        //查询消费者保障服务
        if (C('contract_allow') == 1) {
            $contract_item = Model('contract')->getContractItemByCache();
        }

        foreach ($order_list as $key => $order) {
            //处理消费者保障服务
            if (trim($order['goods_contractid']) && $contract_item) {
                $goods_contractid_arr = explode(',', $order['goods_contractid']);
                foreach ((array)$goods_contractid_arr as $gcti_v) {
                    $order['contractlist'][] = $contract_item[$gcti_v];
                }
            }
            $order_list[$key] = $order;

            //追加返回买家信息
            $order_list[$key]['extend_member'] = Model('member')->getMemberInfoByID($order['buyer_id']);
        }
        foreach ($order_list as $k => $v) {
            $order_list[$k]['goods_img'] = thumb($v, 60);
            $order_list[$k]['time'] = date("Y-m-d H:i:s", $v['add_time']);
        }
        if (!empty($order_list)) {
            echo json_encode(array("list" => $order_list));
        } else {
            echo json_encode(0);
        }
    }

    /**
     * @return array
     * 虚拟订单消费
     */
    public function exchangeOp()
    {
        $member_id = $_SESSION['member_id'];
        // 店铺id
        $condition_store['member_id'] = $member_id;
        $store_online_info = Model('store')->getStoreInfo($condition_store);

        if (!preg_match('/^[a-zA-Z0-9]{0,10}$/', $_GET['vr_code'])) {
            $res = array('code' => '400', 'msg' => '兑换码格式错误，请重新输入');
            echo json_encode($res);
            die;
        }

        $model_vr_order = Model('vr_order');
        $vr_code_info = $model_vr_order->getOrderCodeInfo(array('vr_code' => $_GET['vr_code']));

        if (empty($vr_code_info) || $vr_code_info['store_id'] != $store_online_info['store_id']) {
            $res = array('code' => '400', 'msg' => '该兑换码不存在');
            echo json_encode($res);
            die;
        }
        if ($vr_code_info['vr_state'] == '1') {
            $res = array('code' => '400', 'msg' => '该兑换码已被使用');
            echo json_encode($res);
            die;
        }
        if ($vr_code_info['vr_indate'] < TIMESTAMP) {
            $res = array('code' => '400', 'msg' => '该兑换码已过期，使用截止日期为： ' . date('Y-m-d H:i:s', $vr_code_info['vr_indate']));
            echo json_encode($res);
            die;
        }
        if ($vr_code_info['refund_lock'] > 0) {//退款锁定状态:0为正常,1为锁定(待审核),2为同意
            $res = array('code' => '400', 'msg' => '该兑换码已申请退款，不能使用');
            echo json_encode($res);
            die;
        }
        //更新兑换码状态
        $update = array();
        $update['vr_state'] = 1;
        $update['vr_usetime'] = TIMESTAMP;
        $update = $model_vr_order->editOrderCode($update, array('vr_code' => $_GET['vr_code']));

        //如果全部兑换完成，更新订单状态
        Logic('vr_order')->changeOrderStateSuccess($vr_code_info['order_id']);

        if ($update) {
            //取得返回信息
            $order_info = $model_vr_order->getOrderInfo(array('order_id' => $vr_code_info['order_id']));
            if ($order_info['use_state'] == '0') {
                $model_vr_order->editOrder(array('use_state' => 1), array('order_id' => $vr_code_info['order_id']));
            }
            $order_info['img_60'] = thumb($order_info, 60);
            $order_info['img_240'] = thumb($order_info, 240);
            $order_info['goods_url'] = urlShop('goods', 'index', array('goods_id' => $order_info['goods_id']));
            $order_info['order_url'] = urlShop('store_vr_order', 'show_order', array('order_id' => $order_info['order_id']));
            $order_info['vr_create_time'] = date("Y-m-d", $order_info['add_time']);
            $order_info['vr_code'] = $vr_code_info['vr_code'];
            $res = array('code' => '200', 'data' => $order_info);
            echo json_encode($res);
            die;
        }
    }

    /**
     * 线下订单确认收款
     */
    public function store_reciveOp()
    {
        $order_id = $_POST['order_id'];
        if ($order_id <= 0) {
            output_error('该订单不存在');
        }
        $offline_order = Model('offline_order');
        $condition['order_id'] = $order_id;
        $order = $offline_order->getOrderInfo($condition);
        if (empty($order) || $order['order_state'] == 20) {
            output_error('订单信息错误');
        }
        $updata['recive'] = 1;
        $res = $offline_order->editOrder($updata, $condition);
        if ($res) {
            //处理佣金
            brokerageBill($order);
            output_data(array('status' => 200, 'msg' => "收款成功", 'paySn' => $order['order_sn']));
        } else {
            output_data(array('status' => 400, 'msg' => "收款失败"));
        }
    }


    /**
     * 线下消费详情
     * @return string
     */
    public function offline_order_infoOp()
    {
        $paySn = $_GET['paysn'];
        if (!$paySn) {
            output_error('订单号不能为空');
        }
        $offline_order = Model('offline_order');
        $condition['order_sn'] = $paySn;
        $payOrderInfo = $offline_order->getOrderInfo($condition);
        $payOrderInfo['time'] = date("Y-m-d H:i:s", $payOrderInfo['add_time']);
        output_data(array('orderInfo' => $payOrderInfo));
    }

    private function getGoodsFields()
    {
        return implode(',', array(
            'goods_id',
            'goods_commonid',
            'store_id',
            'store_name',
            'goods_name',
            'goods_price',
            'goods_promotion_price',
            'goods_promotion_type',
            'goods_marketprice',
            'goods_image',
            'goods_salenum',
            'evaluation_good_star',
            'evaluation_count',
            'is_virtual',
            'is_presell',
            'is_fcode',
            'have_gift',
            'goods_addtime',
        ));
    }

    /**
     * 处理商品列表(抢购、限时折扣、商品图片)
     */
    private function _goods_list_extend($goods_list)
    {
        //获取商品列表编号数组
        $goodsid_array = array();
        foreach ($goods_list as $key => $value) {
            $goodsid_array[] = $value['goods_id'];
        }

        $sole_array = Model('p_sole')->getSoleGoodsList(array('goods_id' => array('in', $goodsid_array)));
        $sole_array = array_under_reset($sole_array, 'goods_id');

        foreach ($goods_list as $key => $value) {
            $goods_list[$key]['sole_flag'] = false;
            $goods_list[$key]['group_flag'] = false;
            $goods_list[$key]['xianshi_flag'] = false;
            if (!empty($sole_array[$value['goods_id']])) {
                $goods_list[$key]['goods_price'] = $sole_array[$value['goods_id']]['sole_price'];
                $goods_list[$key]['sole_flag'] = true;
            } else {
                $goods_list[$key]['goods_price'] = $value['goods_promotion_price'];
                switch ($value['goods_promotion_type']) {
                    case 1:
                        $goods_list[$key]['group_flag'] = true;
                        break;
                    case 2:
                        $goods_list[$key]['xianshi_flag'] = true;
                        break;
                }

            }

            //商品图片url
            $goods_list[$key]['goods_image_url'] = cthumb($value['goods_image'], 360, $value['store_id']);

            unset($goods_list[$key]['goods_promotion_type']);
            unset($goods_list[$key]['goods_promotion_price']);
            unset($goods_list[$key]['goods_commonid']);
            unset($goods_list[$key]['nc_distinct']);
        }

        return $goods_list;
    }

    /**
     * 商品评价
     */
    public function store_creditOp()
    {
        $store_id = intval($_GET['store_id']);
        if ($store_id <= 0) {
            output_error('参数错误');
        }
        $store_online_info = Model('store')->getStoreOnlineInfoByID($store_id);
        if (empty($store_online_info)) {
            output_error('店铺不存在或未开启');
        }

        output_data(array('store_credit' => $store_online_info['store_credit']));
    }

    /**
     * 店铺商品排行
     */
    public function store_goods_rankOp()
    {
        $store_id = (int)$_REQUEST['store_id'];
        if ($store_id <= 0) {
            output_data(array());
        }
        $store_online_info = Model('store')->getStoreOnlineInfoByID($store_id);

        $ordertype = ($t = trim($_REQUEST['ordertype'])) ? $t : 'salenumdesc';
        $show_num = ($t = intval($_REQUEST['num'])) > 0 ? $t : 10;

        $where = array();
        $where['store_id'] = $store_id;
        // 默认不显示预订商品
        $where['is_book'] = 0;
        // 排序
        switch ($ordertype) {
            case 'salenumdesc':
                $order = 'goods_salenum desc';
                break;
            case 'salenumasc':
                $order = 'goods_salenum asc';
                break;
            case 'collectdesc':
                $order = 'goods_collect desc';
                break;
            case 'collectasc':
                $order = 'goods_collect asc';
                break;
            case 'clickdesc':
                $order = 'goods_click desc';
                break;
            case 'clickasc':
                $order = 'goods_click asc';
                break;
        }
        if ($order) {
            $order .= ',goods_id desc';
        } else {
            $order = 'goods_id desc';
        }
        $model_goods = Model('goods');
        $goods_fields = $this->getGoodsFields();
        $goods_list = $model_goods->getGoodsListByColorDistinct($where, $goods_fields, $order, 0, $show_num);
        foreach ($goods_list as $key => $v) {
            $goods_list[$key]['store_class'] = $store_online_info['store_class'];
        }
        $goods_list = $this->_goods_list_extend($goods_list);
        output_data(array('goods_list' => $goods_list));
    }

    /**
     * 店铺商品上新
     */
    public function store_new_goodsOp()
    {
        $store_id = (int)$_REQUEST['store_id'];
        if ($store_id <= 0) {
            output_data(array('goods_list' => array()));
        }
        $show_day = ($t = intval($_REQUEST['show_day'])) > 0 ? $t : 30;
        $where = array();
        $where['store_id'] = $store_id;
        $where['is_book'] = 0;//默认不显示预订商品
        $stime = strtotime(date('Y-m-d', time() - 86400 * $show_day));
        $etime = $stime + 86400 * ($show_day + 1);
        $where['goods_addtime'] = array('between', array($stime, $etime));
        $order = 'goods_addtime desc, goods_id desc';
        $model_goods = Model('goods');
        $goods_fields = $this->getGoodsFields();
        $goods_list = $model_goods->getGoodsListByColorDistinct($where, $goods_fields, $order, $this->page);
        $page_count = $model_goods->gettotalpage();
        if ($goods_list) {
            $goods_list = $this->_goods_list_extend($goods_list);
            foreach ($goods_list as $k => $v) {
                $v['goods_addtime_text'] = $v['goods_addtime'] ? @date('Y年m月d日', $v['goods_addtime']) : '';
                $goods_list[$k] = $v;
            }
        }
        output_data(array('goods_list' => $goods_list), mobile_page($page_count));
    }

    /**
     * 店铺简介
     */
    public function store_introOp()
    {
        $store_id = (int)$_REQUEST['store_id'];
        if ($store_id <= 0) {
            output_error('参数错误');
        }
        $store_online_info = Model('store')->getStoreOnlineInfoByID($store_id);
        if (empty($store_online_info)) {
            output_error('店铺不存在或未开启');
        }
        $store_info = $store_online_info;
        //开店时间
        $store_info['store_time_text'] = $store_info['store_time'] ? @date('Y-m-d', $store_info['store_time']) : '';
        // 店铺头像
        $store_info['store_avatar'] = $store_online_info['store_avatar']
            ? UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $store_online_info['store_avatar']
            : UPLOAD_SITE_URL . '/' . ATTACH_COMMON . DS . C('default_store_avatar');
        //商品数
        $store_info['goods_count'] = (int)$store_online_info['goods_count'];
        //店铺被收藏次数
        $store_info['store_collect'] = (int)$store_online_info['store_collect'];
        //店铺所属分类
        $store_class = Model('store_class')->getStoreClassInfo(array('sc_id' => $store_info['sc_id']));
        $store_info['sc_name'] = $store_class['sc_name'];
        //如果已登录 判断该店铺是否已被收藏
        if ($member_id = $this->getMemberIdIfExists()) {
            $c = (int)Model('favorites')->getStoreFavoritesCountByStoreId($store_id, $member_id);
            $store_info['is_favorate'] = $c > 0 ? true : false;
        } else {
            $store_info['is_favorate'] = false;
        }
        // 是否官方店铺
        $store_info['is_own_shop'] = (bool)$store_online_info['is_own_shop'];
        // 页头背景图
        $store_info['mb_title_img'] = $store_online_info['mb_title_img'] ? UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $store_online_info['mb_title_img'] : '';
        // 轮播
        $store_info['mb_sliders'] = array();
        $mbSliders = @unserialize($store_online_info['mb_sliders']);
        if ($mbSliders) {
            foreach ((array)$mbSliders as $s) {
                if ($s['img']) {
                    $s['imgUrl'] = UPLOAD_SITE_URL . DS . ATTACH_STORE . DS . $s['img'];
                    $store_info['mb_sliders'][] = $s;
                }
            }
        }
        output_data(array('store_info' => $store_info));
    }

    /**
     * 店铺促销活动
     */
    public function store_promotionOp()
    {
        $param = $_REQUEST;
        $store_id = (int)$param['store_id'];
        if ($store_id <= 0) {
            output_error('参数错误');
        }
        $fields_arr = array('mansong', 'xianshi');
        $fields_str = trim($param['fields']);
        if ($fields_str) {
            $fields_arr = explode(',', $fields_str);
        }
        $promotion_arr = array();
        if (in_array('mansong', $fields_arr)) {
            //满就送
            $mansong_info = Model('p_mansong')->getMansongInfoByStoreID($store_id);
            if ($mansong_info) {
                $mansong_info['start_time_text'] = date('Y-m-d', $mansong_info['start_time']);
                $mansong_info['end_time_text'] = date('Y-m-d', $mansong_info['end_time']);
                foreach ($mansong_info['rules'] as $rules_k => $rules_v) {
                    $rules_v['goods_image_url'] = cthumb($rules_v['goods_image'], 60);
                    $rules_v['price'] = ncPriceFormat($rules_v['price']);
                    if ($rules_v['discount']) {
                        $rules_v['discount'] = ncPriceFormat($rules_v['discount']);
                    }
                    $mansong_info['rules'][$rules_k] = $rules_v;
                }
                $promotion_arr['mansong'] = $mansong_info;
            }
        }
        if (in_array('xianshi', $fields_arr)) {
            //限时折扣
            $where = array();
            $where['store_id'] = $store_id;
            $where['state'] = 1;
            $where['start_time'] = array('elt', TIMESTAMP);
            $where['end_time'] = array('egt', TIMESTAMP);
            $xianshi_list = Model('p_xianshi')->getXianshiList($where, 0, 'xianshi_id asc', '*', 1);
            if ($xianshi_list) {
                $xianshi_info = $xianshi_list[0];
                $xianshi_info['start_time_text'] = date('Y-m-d', $xianshi_info['start_time']);
                $xianshi_info['end_time_text'] = date('Y-m-d', $xianshi_info['end_time']);
                $promotion_arr['xianshi'] = $xianshi_info;
            }
        }
        output_data(array('promotion' => $promotion_arr));
    }

    /**
     * 记录系统日志
     *
     * @param $lang 日志语言包
     * @param $state 1成功0失败null不出现成功失败提示
     * @param $admin_name
     * @param $admin_id
     */
    protected final function log($lang = '', $state = 1, $admin_name = '', $admin_id = 0)
    {
        if (!C('sys_log') || !is_string($lang)) return;
        if ($admin_name == '') {
            $admin = unserialize(decrypt(cookie('sys_key'), MD5_KEY));
            $admin_name = $admin['name'];
            $admin_id = $admin['id'];
        }
        $data = array();
        if (is_null($state)) {
            $state = null;
        } else {
            $state = $state ? '' : L('nc_fail');
        }
        $data['content'] = $lang . $state;
        $data['admin_name'] = $admin_name;
        $data['createtime'] = TIMESTAMP;
        $data['admin_id'] = $admin_id;
        $data['ip'] = getIp();
        $data['url'] = $_REQUEST['act'] . '&' . $_REQUEST['op'];
        return Model('admin_log')->insert($data);
    }

    /**
     * 统计数量
     * @param $arr 商品数组
     * @param null $field 要统计的字段
     */
    protected function calculateSales($arr)
    {

        $num = '';
        foreach ($arr as $v) {
            $num += $v['goods_salenum'];
        }
        return $num;
    }

    public function store_setOp()
    {
        if (!$_POST['store_id']) {
            output_error('参数错误');
        }
        $where['store_id'] = $_POST['store_id'];
        $data['store_name'] = $_POST['store_name'];
        $data['store_letters'] = $_POST['store_letters'];
        $data['store_description'] = $_POST['store_description'];
        $store_info = Model('store')->getStoreInfo(array('store_id' => $_POST['store_id']));
        if ($_POST['store_avatar']) {
            $data['store_avatar'] = $this->upImgs([$_POST['store_avatar']], BASE_UPLOAD_PATH . '/shop/store')[0];
        }
        if ($_POST['store_banner']) {
            $imags = [];
            // 过滤掉非上传的图片
            foreach ($_POST['store_banner'] as $v) {
                $fix = substr($v, 0, strripos($v, 'image') + 5);
                if ($fix == 'data:image') {
                    $imags[] = $v;
                }
            }
            $imageFile = $this->upImgs($imags, BASE_UPLOAD_PATH . '/shop/banner');

            $cutImage = [];
            foreach ($imageFile as $v) {
                $subfix = substr($v, strripos($v, '.') + 1);
                $name = substr($v, 0, strripos($v, '.'));
                $dsrc = BASE_UPLOAD_PATH . '/shop/banner/' . $name . "_400_250." . $subfix;
                $this->resize(BASE_UPLOAD_PATH . '/shop/banner/' . $v, $dsrc, 400, 250);
                unlink(BASE_UPLOAD_PATH . '/shop/banner/' . $v);
                $cutImage[] = basename($dsrc);
            }
            if ($store_info['m_store_banner']) {
                $data['m_store_banner'] = $store_info['m_store_banner'] . "," . implode(',', $cutImage);
            } else {
                $data['m_store_banner'] = implode(',', $cutImage);
            }
        }
        $model_store = Model('store');
        $res = $model_store->editStore($data, $where);
        $msg = '保存成功！';
        if (!$res) {
            $msg = '保存失败！';
        }
        output_data(array('msg' => $msg));
    }


    /**
     *上传多图  仅限 base64
     * @param $imgs
     * @param bool|false $dir 路径
     * @param bool|true $isdel
     * @return string
     */
    public function upImgs($imgs, $dir = false)
    {
        $dir = $dir ? $dir : date('Ymd');
        $res = [];
        foreach ($imgs as $k => $v) {
            if (file_exists($v)) {
                $res[$k] = $v;
            } else {
                $v = explode(',', $v);
                $imgpath = $dir . "/";
                preg_match('/image\/(.*);base64/u', $v[0], $imgtype);
                $imgtype = $imgtype[1] == "jpeg" ? 'jpg' : $imgtype[1];
                if (!file_exists($imgpath)) {
                    mkdir($imgpath);
                }
                list($usec, $sec) = explode(" ", microtime());
                $imgname = $sec . str_replace('0.', '_', $usec);
                $imgname = $imgname . '.' . $imgtype;
                $base64 = base64_decode(end($v));
                $save = file_put_contents($imgpath . $imgname, $base64);
                if ($save) {
                    $res[] = $imgname;
                }
            }
        }
        return $res;
    }

    /**
     * 获取店铺与我距离
     */
    public function getStoreDistansOp()
    {
        $x = $_POST['x'];
        $y = $_POST['y'];
        $store_id = $_POST['store_id'];
        $distans['_index'] = $_POST['i'];
        $model_store_map = Model('store_map');
        $condition['store_id'] = $store_id;
        $map_list = $model_store_map->getStoreMapList($condition, 10, '', 'map_id asc');
        // 判断是否存在多个地点
        if (!empty($map_list) && is_array($map_list)) {
            $map_distans = array();
            foreach ($map_list as $v) {
                $store_lng = $v['baidu_lng'];
                $store_lat = $v['baidu_lat'];
                $distanss = $this->getDistance($x, $y, $store_lat, $store_lng);
                $map_distans[] = $distanss;
            }
            $pos = array_search(min($map_distans), $map_distans);
            $distans['distans'] = $map_distans[$pos];
        }
        output_data($distans);
    }

    /**
     * @desc 根据两点间的经纬度计算距离
     * @param float $lat 纬度值
     * @param float $lng 经度值
     */
    private function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000; //approximate radius of earth in meters

        /*
        Convert these degrees to radians
        to work with the formula
        */

        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;

        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;

        /*
        Using the
        Haversine formula

        http://en.wikipedia.org/wiki/Haversine_formula

        calculate the distance
        */

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
    }

    /**
     * 商户保存图片
     */
    public function savepicsOp()
    {
        $store_info = Model('store')->getStoreInfo(array('store_id' => $_POST['store_id']));
        if ($_POST['pics']) {
            $imags = [];
            // 过滤掉非上传的图片
            foreach ($_POST['pics'] as $v) {
                $fix = substr($v, 0, strripos($v, 'image') + 5);
                if ($fix == 'data:image') {
                    $imags[] = $v;
                }
            }
            $imageFile = $this->upImgs($imags, BASE_UPLOAD_PATH . '/shop/banner');

            $cutImage = [];
            foreach ($imageFile as $v) {
                $subfix = substr($v, strripos($v, '.') + 1);
                $name = substr($v, 0, strripos($v, '.'));
                $dsrc = BASE_UPLOAD_PATH . '/shop/banner/' . $name . "_400_250." . $subfix;
                $this->resize(BASE_UPLOAD_PATH . '/shop/banner/' . $v, $dsrc, 400, 250);
                unlink(BASE_UPLOAD_PATH . '/shop/banner/' . $v);
                $cutImage[] = basename($dsrc);
            }
            if ($store_info['m_store_banner']) {
                $data['m_store_banner'] = $store_info['m_store_banner'] . "," . implode(',', $cutImage);
            } else {
                $data['m_store_banner'] = implode(',', $cutImage);
            }
        }
        $where['store_id'] = $_POST['store_id'];
        $model_store = Model('store');
        $res = $model_store->editStore($data, $where);
        $data['m_store_banners'] = explode(',', $data['m_store_banner']);
        $status = 200;
        $msg = '保存成功！';
        if (!$res) {
            $status = 400;
            $msg = '保存失败！';
        }

        output_data(array('status' => $status, 'msg' => $msg, 'store_info' => $data));
    }

    /**
     * 线下支付店铺信息
     */
    public function offline_store_infoOp()
    {
        $store_id = $_POST['store_id'];;
        $store_online_info = Model('store')->getStoreOnlineInfoByID($store_id);
        if (empty($store_online_info)) {
            output_error('店铺不存在或未开启');
        }
        $store_info = array();
        $store_info['store_id'] = $store_online_info['store_id'];
        $store_info['store_name'] = $store_online_info['store_name'];
        $store_info['member_id'] = $store_online_info['member_id'];
        $store_info['class_store'] = $store_online_info['store_class'];

        // 店铺头像
        $store_info['store_avatar'] = $store_online_info['store_avatar']
            ? UPLOAD_SITE_URL . '/' . ATTACH_STORE . '/' . $store_online_info['store_avatar']
            : UPLOAD_SITE_URL . '/' . ATTACH_COMMON . DS . C('default_store_avatar');
        $member_id = $this->getMemberIdIfExists();
        $model_member = Model('member');
        $member_info = $model_member->getMemberInfoByID($member_id);
        output_data(['store_info' => $store_info, 'member_info' => $member_info]);
    }

    /**
     * 线下店铺支付二维码
     */
    public function offline_store_qrcodeOp()
    {
        $store_id = $_POST['store_id'];;
        $store_online_info = Model('store')->getStoreOnlineInfoByID($store_id);
        $myurl = BASE_SITE_URL . "/wap/tmpl/member/offline_pay.html?store_id=" . $store_id;
        $str_store = "offline_storeqr_" . $store_id;
        $myurl_src = UPLOAD_SITE_URL . DS . "shop" . DS . "store" . DS . $str_store . '.png';
        $imgfile = BASE_UPLOAD_PATH . DS . "shop" . DS . "store" . DS . $str_store . '.png';
        if (!file_exists($imgfile)) {
            require_once(BASE_RESOURCE_PATH . DS . 'phpqrcode' . DS . 'index.php');
            $PhpQRCode = new PhpQRCode();
            $PhpQRCode->set('pngTempDir', BASE_UPLOAD_PATH . DS . "shop" . DS . "store" . DS);
            $PhpQRCode->set('date', $myurl);
            $PhpQRCode->set('pngTempName', $str_store . '.png');
            $PhpQRCode->init();
        }
        $store_info['url'] = $myurl;
        $store_info['qrcode'] = $myurl_src;
        $store_info['store_name'] = $store_online_info['store_name'];
        output_data(array('store_info' => $store_info));
    }

    /**
     * 小店广告图删除
     */
    public function bannerdelOp()
    {
        $store = $_POST['store_id'];
        $src = $_POST['src'];
        $store_info = Model('store')->getStoreInfo(array('store_id' => $store));
        $banners = explode(',', $store_info['m_store_banner']);
        foreach ($banners as $k => $v) {
            if ($src == $v) {
                array_splice($banners, $k, 1);
                unlink(BASE_UPLOAD_PATH . '/shop/banner/' . $v);
            }
        }
        if (empty($banners)) {
            $updata['m_store_banner'] = '';
        } else {
            $updata['m_store_banner'] = implode(',', $banners);
        }
        $res = Model('store')->editStore($updata, array('store_id' => $store));
        $data['m_store_banners'] = $banners;
        if ($res) {
            $res = ['status' => 200, 'msg' => '删除成功', 'store_info' => $data];
        } else {
            $res = ['status' => 200, 'msg' => '删除失败'];
        }
        output_data($res);
    }

    /**
     * *
     *等比缩放
     * @param unknown_type $srcImage 源图片路径
     * @param unknown_type $toFile 目标图片路径
     * @param unknown_type $maxWidth 最大宽
     * @param unknown_type $maxHeight 最大高
     * @param unknown_type $imgQuality 图片质量
     * @return unknown
     */
    function resize($srcImage, $toFile, $maxWidth = 100, $maxHeight = 100, $imgQuality = 100)
    {

        list($width, $height, $type, $attr) = getimagesize($srcImage);
        if ($width < $maxWidth || $height < $maxHeight) return;
        switch ($type) {
            case 1:
                $img = imagecreatefromgif($srcImage);
                break;
            case 2:
                $img = imagecreatefromjpeg($srcImage);
                break;
            case 3:
                $img = imagecreatefrompng($srcImage);
                break;
        }
        $scale = min($maxWidth / $width, $maxHeight / $height); //求出绽放比例

        if ($scale < 1) {
            $newWidth = floor($scale * $width);
            $newHeight = floor($scale * $height);
            $newImg = imagecreatetruecolor($newWidth, $newHeight);
            imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
            $newName = "";
            $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i", "", $toFile);

            switch ($type) {
                case 1:
                    if (imagegif($newImg, "$toFile$newName.gif"))
                        return "$newName.gif";
                    break;
                case 2:
                    if (imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
                        return "$newName.jpg";
                    break;
                case 3:
                    if (imagepng($newImg, "$toFile$newName.png"))
                        return "$newName.png";
                    break;
                default:
                    if (imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
                        return "$newName.jpg";
                    break;
            }
            imagedestroy($newImg);
        }
        imagedestroy($img);
        return false;
    }
}
